<?php


namespace app\backend\middleware;
use app\common\RootMiddleware;

class AuthMiddleware extends RootMiddleware
{
    public function handle($request, \Closure $next)
    {
        // 控制器名称
        $controller = $request->controller();
        // 从cookie里面提取token
        $accessToken = $request->cookie('accessToken');
        // token校验
        $tokenVerify = $this->checkToken($accessToken);
        // token过期跳转到登录页面
        if (!in_array($controller, ['Login', 'NoStateCode']) && !$tokenVerify) {
            if ($request->isAjax()) {
                return json(['code' => 1, 'msg' => 'token失效，请刷新页面重新登录!']);
            }
            return redirect(url('Login/index'));
        }
        // 登录校验
        if (in_array($controller, ['Login']) && $tokenVerify) {
            return redirect(url('Index/index'));
        }
        // 默认流程
        return $next($request);
    }
}